package com.wanyang.service;

import com.wanyang.bo.MemberBO;
import com.wanyang.dos.MemberDO;
import com.wanyang.exception.ApiException;
import com.wanyang.mapper.MemberDOMapper;
import com.wanyang.vo.AuthVO;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AuthServiceImpl implements AuthService {
    @Resource
    private MemberDOMapper memberDOMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private JwtTokenHelper jwtTokenHelper;

    @Autowired
    private SmsService smsService;

    @Override
    public AuthVO login(String mobile, String smsCode) {
        boolean validResult = smsService.validSmsCode(mobile, smsCode, SmsService.loginScenes);

        if (!validResult) {
            throw new ApiException("验证码不正确");
        }

        MemberDO memberDO = memberService.getModel(mobile);

        if (memberDO == null) {
            throw new ApiException("用户不存在");
        }

        return genAuthVO(memberDO);
    }

    @Override
    public AuthVO register(String mobile, String smsCode, String shareCode) {
        boolean validResult = smsService.validSmsCode(mobile, smsCode, SmsService.registerScenes);

        if (!validResult) {
            throw new ApiException("验证码不正确");
        }

        MemberDO memberDO = memberService.register(mobile, shareCode);

        return genAuthVO(memberDO);
    }

    @Override
    public AuthVO refresh(String refreshToken) {
        if (jwtTokenHelper.isTokenExpired(refreshToken)) {
            throw new ApiException("refreshToken expired", 501);
        }

        Claims claims = jwtTokenHelper.getClaimsFromToken(refreshToken);
        Integer memberId = claims.get(JwtTokenHelper.CLAIM_KEY_USERID, Integer.class);
        String type = claims.get(JwtTokenHelper.CLAIM_KEY_TYPE, String.class);

        MemberBO memberBO = memberService.getMemberBO(memberId);

        if (memberBO == null || !"refresh".equals(type)) {
            throw new ApiException("invalid token", 501);
        }


        return genAuthVO(memberBO);
    }

    private AuthVO genAuthVO(MemberDO memberDO) {
        AuthVO authVO = new AuthVO();
        authVO.setMemberId(memberDO.getId());
        authVO.setToken(jwtTokenHelper.generateToken(memberDO));
        authVO.setRefreshToken(jwtTokenHelper.generateRefreshToken(memberDO));
        return authVO;
    }

}
